//
//  MyOrderViewController.m
//  bitcoin
//
//  Created by  旺链 on 2018/5/28.
//  Copyright © 2018年 比特币. All rights reserved.
//

#import "MyOrderViewController.h"
#import "CurrentDeputeTableViewCell.h"
#import "HistoryDeputeTableViewCell.h"
#import "FilterView.h"
#import "BusinessDetailViewController.h"
#import "MJRefresh.h"

#define pageSize 10
typedef NS_ENUM(NSInteger,BussinessType){
    BussinessTypeBuy = 1,
    BussinessTypeSold,
    BussinessTypeAll
};

@interface MyOrderViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
{
    NSArray *btnArr;
}
//@property(nonatomic,strong)UIView *footView;

@property(strong,nonatomic)NSString *currencyPay;
@property(strong,nonatomic)NSString *currencyTrade;
@property(assign,nonatomic)BussinessType bussinessType;

@property(assign,nonatomic)NSInteger currentPageNum;
@property(assign,nonatomic)NSInteger historyPageNum;

@property(nonatomic,strong)UIScrollView *backScroll;
@property(nonatomic,strong)UITableView *currentTable;
@property(nonatomic,strong)UITableView *historyTable;

@property(nonatomic,strong)FilterView *filtView;

@property(nonatomic,strong)UIButton *selectBtn;

@property(nonatomic,strong)NSMutableArray *currentArr;
@property(nonatomic,strong)NSMutableArray *historyArr;

@property(nonatomic,copy)MJRefreshAutoNormalFooter *currentFooter;
@property(nonatomic,copy)MJRefreshAutoNormalFooter *historyFooter;

@end


@implementation MyOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的订单";
    
    self.currentPageNum = 1;
    self.historyPageNum = 1;
    self.bussinessType = 3;
    self.currencyPay = @"";
    self.currencyTrade = @"";
    
    [self addRight];
    [self addBtn];
    [self.view addSubview:self.backScroll];
    [self getData];
}

- (void)addRight
{
    UIButton *btn = [[UIButton alloc] init];
    btn.frame = CGRectMake(0, 0, 50, 64);
    [btn setImage:[UIImage imageNamed:@"shai-icon"] forState:UIControlStateNormal];
    [btn setTitle:@" 筛选" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithHexString:@"#737582"] forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:14]];
//    [btn setTitle:@"             " forState:UIControlStateNormal];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    [btn addTarget:self action:@selector(filter) forControlEvents:UIControlEventTouchUpInside];
    
//    self.leftButton = btn;
    //    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowleft-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    self.navigationItem.rightBarButtonItem = backItem;
}
- (void)filter
{
    [self.view addSubview:self.filtView];
}

- (void)addBtn
{
    UIButton *current = [[UIButton alloc]initWithFrame:CGRectMake(0, 1, ScreenWidth/2, 44)];
    current.titleLabel.font = [UIFont systemFontOfSize:16];
    [current setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
    [current setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateSelected];
    [current setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#25293D"]] forState:UIControlStateNormal];
    [current setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#7B4EE1"]] forState:UIControlStateSelected];
    [current setTitle:@"当前委托" forState:UIControlStateNormal];
    current.tag = 100;
    [current addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:current];
    
    UIButton *history = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/2, 1, ScreenWidth/2, 44)];
    history.titleLabel.font = [UIFont systemFontOfSize:16];
    [history setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
    [history setTitleColor:[UIColor colorWithHexString:@"#FFFFFF"] forState:UIControlStateSelected];
    [history setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#25293D"]] forState:UIControlStateNormal];
    [history setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#7B4EE1"]] forState:UIControlStateSelected];
    [history setTitle:@"历史委托" forState:UIControlStateNormal];
    history.tag = 101;
    [history addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:history];
    
    btnArr = @[current,history];
    
    self.selectBtn = current;
}
- (void)btnClick:(UIButton *)btn
{
    [self showSelect:btn];
    
    if ((btn.tag-100)==0) {
        //当前委托
        [self.backScroll setContentOffset:CGPointMake(0, 0) animated:YES];
    }else{
        //历史委托
        [self.backScroll setContentOffset:CGPointMake(ScreenWidth, 0) animated:YES];
    }
}
- (void)showSelect:(UIButton *)btn
{
    for (UIButton *b in btnArr) {
        b.selected = NO;
    }
    self.selectBtn = btn;
}
- (void)getData
{
    [self getCurrentOrder];
    [self getHistoryOrder];
}

- (void)getCurrentOrder
{
    NSDictionary *para = @{@"pageSize":@pageSize,@"pageNum":@(self.currentPageNum),@"businessType":@(self.bussinessType),@"currencyPay":self.currencyPay,@"currencyTrade":self.currencyTrade};
    [LSRequestManager postRequestWithURL:MARKET(@"listPersonalOrderCurrent") params:para success:^(NSDictionary *responseData) {
        
        if (self.currentArr.count == 0) {
            self.currentTable.tableFooterView = nil;
        }
        [self.currentTable.mj_header endRefreshing];
        [self.currentTable.mj_footer endRefreshing];
        
        
        HandleResponse(
                       if (![responseData[@"data"][@"listOrderVO"] isKindOfClass:[NSArray class]]) {
                           self.currentTable.tableFooterView = self.footView;
                           self.currentTable.mj_footer = nil;
                           return ;
                       }
                       
                       [self.currentArr addObjectsFromArray:responseData[@"data"][@"listOrderVO"]];
                       
                       
                       if (self.currentArr.count == 0) {
                           self.currentTable.tableFooterView = self.footView;
                           self.currentTable.mj_footer = nil;
                       }else{
                           self.currentTable.tableFooterView = [UIView new];
                           self.currentTable.mj_footer = self.currentFooter;
                       }
                       if (self.currentArr.count <pageSize) {
                           self.currentTable.mj_footer = nil;
                       }
                       
                       [self.currentTable reloadData];
                       
                       )
        NSLog(@"11");
    }
    } failure:^(NSError *error) {
        [self.currentTable.mj_header endRefreshing];
        [self.currentTable.mj_footer endRefreshing];
    }];
}
- (void)getHistoryOrder
{
    NSDictionary *para = @{@"pageSize":@pageSize,@"pageNum":@(self.historyPageNum),@"businessType":@(self.bussinessType),@"currencyPay":self.currencyPay,@"currencyTrade":self.currencyTrade};
    [LSRequestManager postRequestWithURL:MARKET(@"listPersonalOrderHistory") params:para success:^(NSDictionary *responseData) {
        
        [self.historyTable.mj_header endRefreshing];
        [self.historyTable.mj_footer endRefreshing];
        
        HandleResponse(
                       [self.historyArr addObjectsFromArray:responseData[@"data"][@"listOrderVO"]];
                       
                       if (self.historyArr.count == 0) {
                           self.historyTable.tableFooterView = self.footView;
                           self.historyTable.mj_footer =nil;
                       }else{
                           self.historyTable.tableFooterView = nil;
                           self.historyTable.mj_footer = self.historyFooter;
                       }
                       if (self.currentArr.count <pageSize) {
                           self.currentTable.mj_footer = nil;
                       }
                       [self.historyTable reloadData];
        
                       )}
    } failure:^(NSError *error) {
        
        [self.historyTable.mj_header endRefreshing];
        [self.historyTable.mj_footer endRefreshing];
    }];
}
#pragma mark 筛选
- (FilterView *)filtView
{
    if (!_filtView) {
        
        _filtView = [[[NSBundle mainBundle]loadNibNamed:@"FilterView" owner:self options:nil]firstObject];
        _filtView.frame = self.view.bounds;
        
        MJWeakSelf;
        _filtView.filterBaclk = ^(NSDictionary *dic) {
          
            weakSelf.currencyTrade = dic[@"currencyTrade"];
            weakSelf.currencyPay = dic[@"currencyPay"];
            weakSelf.bussinessType = (BussinessType)[dic[@"businessType"]integerValue];
            
            if ((self.selectBtn.tag-100)==0) {
                //当前委托
                
                [weakSelf.currentArr removeAllObjects];
                [weakSelf.currentTable reloadData];
                weakSelf.currentPageNum = 1;
                [weakSelf getCurrentOrder];
            }else{
                //历史委托
                [weakSelf.historyArr removeAllObjects];
                [weakSelf.historyTable reloadData];
                weakSelf.historyPageNum = 1;
                [weakSelf getHistoryOrder];
            }
            
            [weakSelf.filtView removeFromSuperview];
        };
    }
    return _filtView;
}
- (MJRefreshAutoNormalFooter *)currentFooter
{
    if (!_currentFooter) {
        _currentFooter = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            self.currentPageNum++;
            [self getCurrentOrder];
        }];
    }
    return _currentFooter;
}
- (MJRefreshAutoNormalFooter *)historyFooter
{
    if (!_historyFooter) {
        _historyFooter = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            self.historyPageNum++;
            [self getHistoryOrder];
        }];
    }
    return _historyFooter;
}
- (UIScrollView *)backScroll
{
    if (!_backScroll) {
        _backScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 44, ScreenWidth, ScreenHeight-44)];
        _backScroll.contentSize = CGSizeMake(ScreenWidth*2, ScreenHeight-44);
        _backScroll.pagingEnabled = YES;
        _backScroll.delegate = self;
        [_backScroll addSubview:self.currentTable];
        [_backScroll addSubview:self.historyTable];
    }
    return _backScroll;
}
- (UITableView *)currentTable
{
    if (!_currentTable) {
        _currentTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, self.backScroll.mm_height-65) style:UITableViewStylePlain];
        _currentTable.delegate = self;
        _currentTable.dataSource = self;
      //  _currentTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _currentTable.backgroundColor = [UIColor clearColor];
        _currentTable.tableFooterView = [UIView new];
        [_currentTable registerNib:[UINib nibWithNibName:@"CurrentDeputeTableViewCell" bundle:nil] forCellReuseIdentifier:@"CurrentDeputeTableViewCell"];
        
        _currentTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
           
            [self.currentArr removeAllObjects];
            self.currentPageNum = 1;
            [self getCurrentOrder];
        }];
//        _currentTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//
//            self.currentPageNum++;
//            [self getCurrentOrder];
//        }];

    }
    return _currentTable;
}
- (UITableView *)historyTable
{
    if (!_historyTable) {
        _historyTable = [[UITableView alloc]initWithFrame:CGRectMake(ScreenWidth, 0, ScreenWidth, self.backScroll.mm_height-65) style:UITableViewStylePlain];
        _historyTable.delegate = self;
        _historyTable.dataSource = self;
        _historyTable.backgroundColor = [UIColor clearColor];
        _historyTable.tableFooterView = [UIView new];
        [_historyTable registerNib:[UINib nibWithNibName:@"HistoryDeputeTableViewCell" bundle:nil] forCellReuseIdentifier:@"HistoryDeputeTableViewCell"];
        
        _historyTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [self.historyArr removeAllObjects];
            self.historyPageNum = 1;
            [self getHistoryOrder];
        }];
//        _historyTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//
//            self.historyPageNum++;
//            [self getHistoryOrder];
//        }];

    }
    return _historyTable;
}
- (UIView *)footView
{
    
        
        UIView *_footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];
        UILabel *la = [[UILabel alloc]initWithFrame:_footView.frame];
        la.textColor = [UIColor whiteColor];
        la.text = @"暂无数据";
        la.textAlignment = NSTextAlignmentCenter;
        [_footView addSubview:la];
    
    return _footView;
}
- (NSMutableArray *)currentArr
{
    if (!_currentArr) {
        _currentArr = [NSMutableArray array];
    }
    return _currentArr;
}
- (NSMutableArray *)historyArr
{
    if (!_historyArr) {
        _historyArr = [NSMutableArray array];
    }
    return _historyArr;
}
- (void)setSelectBtn:(UIButton *)selectBtn
{
    _selectBtn = selectBtn;
    _selectBtn.selected = YES;
}

#pragma mark UIScrollViewdelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.backScroll) {
        
        NSLog(@"%f",scrollView.contentOffset.x);
        NSInteger index = scrollView.contentOffset.x/ScreenWidth;
        
        [self showSelect:btnArr[index]];
    }
}
#pragma mark UITableViewdelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.currentTable) {
        
        return self.currentArr.count;
    }else{
        return self.historyArr.count;
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTable) {
        CurrentDeputeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CurrentDeputeTableViewCell"];
        
        NSDictionary *dic = self.currentArr[indexPath.row];
        [cell configWidthData:dic];
        
        //撤单
        cell.unDoBack = ^{
            
            [self unDoPost:dic[@"id"]];
        };
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        HistoryDeputeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryDeputeTableViewCell"];
        
        NSDictionary *dic = self.historyArr[indexPath.row];
        [cell configWidthData:dic];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.showDetail = ^{
            
            BusinessDetailViewController *business = [[BusinessDetailViewController alloc]init];
            business.data = dic;
            [self.navigationController pushViewController:business animated:YES];
        };
        
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTable) {
        return 100;
    }else{
        return 175;
    }
    
}
- (void)unDoPost:(NSString*)orderid
{
    [LSRequestManager postRequestWithURL:MARKET(@"undoOrder") params:@{@"orderId":orderid} success:^(NSDictionary *responseData) {
        
        HandleResponse(
        
                       [MBProgressHUD showError:responseData[@"msg"]];
                       
                       //刷新列表
                       [self.currentArr removeAllObjects];
                       self.currentPageNum = 1;
                       [self getCurrentOrder];
                       
                       [self.historyArr removeAllObjects];
                       self.historyPageNum = 1;
                       [self getHistoryOrder];
                       )}
    } failure:^(NSError *error) {
        
    } showHUD:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
